﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;
using System.Threading;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.IO;

namespace bulkDeployment
{
    public partial class frm1 : Form
    {
        public frm1()
        {
            InitializeComponent();
            this.btnDeploy.Enabled = false;
            this.btnChangeVPath.Enabled = false;
        }
        private string url = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            getWebApps(false,false);
            getZones();
            lblWarning.Text = "WARNING" + Environment.NewLine +
                "This will change your virtual directory for your web application." + Environment.NewLine +
                "If you manually changed your virtual directory and get somthing similar to the following error: " + Environment.NewLine + Environment.NewLine +
                "'Error: The web.config is missing from this IIS Web Site: c:\\inetpub\\wwwroot\\web.config' " + Environment.NewLine + Environment.NewLine +
                "but you know it exists at 'C:\\Inetpub\\wwwroot\\wss\\VirtualDirectories\\80'"+ Environment.NewLine+
                "Using this tool you can change the directory to point to the new location." + Environment.NewLine + Environment.NewLine +
                "1) You need to first enter the url for the given web application that you want to change." + Environment.NewLine +
                "2) You now need to click on the button to select the new path where the web application currently exists" + Environment.NewLine + Environment.NewLine +
                "Only do this if you changed the virtual directory location manually and need to update sharepoint";
        }

        private void getWebApps(bool getURL, bool cb1)
        {
            SPServiceCollection services = SPFarm.Local.Services;

            foreach (SPService curService in services)
            {
                if (curService is SPWebService)
                {
                    SPWebService webService = (SPWebService)curService;

                    foreach (SPWebApplication webApp in webService.WebApplications)
                    {
                        if (getURL == false)
                        {
                            if (webApp.Name != "")
                            {
                                this.cbbwebApps1.Items.Add(webApp.Name);
                                this.cbbwebApps2.Items.Add(webApp.Name);
                            }
                        }
                        else
                        {
                            if (cb1 == true)
                            {
                                if (webApp.Name == this.cbbwebApps1.SelectedItem.ToString())
                                {
                                    url = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri;
                                }
                            }
                            else
                            {
                                if (webApp.Name == this.cbbwebApps2.SelectedItem.ToString())
                                {
                                    url = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri;
                                }
                            }
                        }
                    }
                }
            }
        }

        private void btnDeploy_Click(object sender, EventArgs e)
        {
            this.btnDeploy.Enabled = false;

            if (txtLogging.Text != "")
            {
                txtLogging.Clear();
            }

            executeSolution(true);
        }

        private void executeSolution(bool add)
        {
            try
            {                        
                Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
                SPWebApplication webapp = SPWebApplication.Lookup(new Uri(url));
                webapps.Add(webapp);

                SPSolutionCollection spSC = SPFarm.Local.Solutions;
                foreach (SPSolution spSolution in spSC)
                {

                    if (spSolution.ContainsWebApplicationResource)
                    {
                        if (add == true)
                        {
                            //deploy
                            spSolution.Deploy(DateTime.Now, true, webapps, true);
                            //logging
                            txtLogging.Text += spSolution.DisplayName + " to " + url + Environment.NewLine;
                        }
                        else
                        {
                            foreach (SPWebApplication weba in spSolution.DeployedWebApplications)
                            {
                                if (weba.Name == webapps[0].Name)
                                {
                                    //retract
                                    spSolution.Retract(DateTime.Now, webapps);
                                    //logging
                                    txtdebug.Text += spSolution.DisplayName + " removed from " + url + Environment.NewLine;
                                    break;
                                }
                            }
                            
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.btnDeploy.Enabled = true;
            MessageBox.Show("Done, Please give it time for all the webparts that have been deployed to deploy." + Environment.NewLine + "Depending on the ammount of webparts deployed will determin how long it will take." + Environment.NewLine + "You will notice your web app performe an iisreset for each deployed webpart");
        }

        private void btnChangeVPath_Click(object sender, EventArgs e)
        {
            updateVirtualPath();
        }

        private void getZones()
        {
            this.cbburlzone.Items.Add(SPUrlZone.Default);
            this.cbburlzone.Items.Add(SPUrlZone.Custom);
            this.cbburlzone.Items.Add(SPUrlZone.Extranet);
            this.cbburlzone.Items.Add(SPUrlZone.Internet);
            this.cbburlzone.Items.Add(SPUrlZone.Intranet);
            this.cbburlzone.SelectionStart = 0;
        }

        private void updateVirtualPath()
        {
            this.btnChangeVPath.Enabled = false;
            try
            {
                using (SPSite site = new SPSite(this.txtUrl.Text))
                {
                    //get site's web application IIS Settings
                    SPIisSettings iisSettings = site.WebApplication.IisSettings[(SPUrlZone)this.cbburlzone.SelectedItem];
                    string folderPath = string.Empty;

                    using (FolderBrowserDialog fdb = new FolderBrowserDialog()) 
                    {
                        fdb.SelectedPath = @"C:\Inetpub\wwwroot\wss\VirtualDirectories\";
                        if (fdb.ShowDialog() == DialogResult.OK )
                        {
                            folderPath = fdb.SelectedPath;
                            
                            iisSettings.Path = new System.IO.DirectoryInfo(@folderPath);

                            //Call the Update method of the web application
                            site.WebApplication.Update();

                            MessageBox.Show("Your new virtual path has been changed to " + folderPath);

                            this.btnChangeVPath.Enabled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Invalid URI: The format of the URI could not be determined.")
                {
                    MessageBox.Show("You must enter a valid URL with http(s)://");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void txtUrl_TextChanged(object sender, EventArgs e)
        {
            if (txtUrl.Text.Length != 0)
            {
                this.btnChangeVPath.Enabled = true;
            }
            else
            {
                this.btnChangeVPath.Enabled = false;
            }
        }

        private void cbbwebApps2_SelectedIndexChanged(object sender, EventArgs e)
        {
            getWebApps(true,false);
            this.btnDeploy.Enabled = true;
        }

        private void btnRemoveWebApp_Click(object sender, EventArgs e)
        {
            this.btnDeploy.Enabled = false;

            if (txtLogging.Text != "")
            {
                txtLogging.Clear();
            }

            executeSolution(false);
        }

        private void cbbwebApps1_SelectedIndexChanged(object sender, EventArgs e)
        {
            getWebApps(true,true);
            this.btnDeploy.Enabled = true;
        }
    }
}
